<?php
class M_DbTable_Order extends Apps_Db_Table_Abstract {
	protected $_name = 'order';

	const REFERENCE_TYPE_TOUR 	= 1;
	const REFERENCE_TYPE_CRUISE = 3;
	const REFERENCE_TYPE_NOT_DEFINE	= 0;

	public function listReferenceByOrderType($referenceType) {
		$select =  $this->_db
						->select();
		switch ($referenceType) {
			case self::REFERENCE_TYPE_TOUR:
				$select->from('tour', null)
				  	   ->join('article', 'article.reference_id = tour.id', null)
					   ->columns(array(
							'id'	=> 'tour.id',
							'name'	=> 'article.title'
					   ));
				break;
			case self::REFERENCE_TYPE_CRUISE:
				$select->from('cruise')
					   ->columns(array(
							'id'	=> 'cruise.id',
							'name'	=> 'cruise.name'
					   ));;
				break;

			default: break;
		}

		return $select->query()->fetchAll();
	}

	public function getList() {
		$q = $this->_db
				  ->select()
				  ->from('order', null)
				  ->join('payment_type', 'payment_type.id = order.payment_type_id', null)
				  ->join('order_status', 'order_status.id = order.order_status_id', null)
				  ->joinLeft('customer', 'customer.id = order.customer_id', null)
				  ->joinLeft('tour', 'order.reference_type = '. self::REFERENCE_TYPE_TOUR . ' AND tour.id = order.reference_id', null)
				  ->joinLeft('cruise', 'order.reference_type = '. self::REFERENCE_TYPE_CRUISE . ' AND cruise.id = order.reference_id', null)
				  ->joinLeft('article', 'article.reference_id = tour.id', null)
				  ->columns(array(
				  		'tour_id'		=> 'tour.id',
				  		'tour_title'	=> 'article.title',
				  		'cruise_id'		=> 'cruise.id',
				  		'cruise_name'	=> 'cruise.name'
				  ));

		$q->columns(array(
	  			'id'					=> 'order.id',
	  			'customer_id'			=> 'customer.id',
				'customer_name'			=> 'customer.full_name',
	  			'email'					=> 'customer.email',
	  			'phone'					=> 'customer.phone',
	  			'address'				=> 'customer.address',
	  			'country_residence'		=> 'customer.country_residence',
	  			'reference_type'		=> 'order.reference_type',
				'payment_type'			=> 'payment_type.title',
				'order_status'			=> 'order_status.title',
				'description'			=> 'order.description'
	  		));
		return $q;
	}
}